package cn.edu.lsu.integratedsurvey.controller;

import cn.edu.lsu.integratedsurvey.bean.dto.StudentRegisterDto;
import cn.edu.lsu.integratedsurvey.bean.vo.StudentInfoVo;
import cn.edu.lsu.integratedsurvey.service.StudentService;
import cn.edu.lsu.integratedsurvey.tool.JwtUtil;
import cn.edu.lsu.integratedsurvey.tool.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * @author Jasmine-drs
 * @date 2024/5/1 20:14
 */

@Slf4j
@Api("学生模块")
@RestController
@RequestMapping("/students")
public class StudentController {

    final JwtUtil jwtUtil;//    jwt鉴权的工具类，判断是否是管理员（admin）或者root
    final StudentService studentService;

    public StudentController(JwtUtil jwtUtil, StudentService studentService) {
        this.jwtUtil = jwtUtil;
        this.studentService = studentService;
    }


    /**
     * 通过学号获取学生信息
     *
     * @param studentNumber 学号
     * @return 综测信息
     */
    @GetMapping("/get/{studentNumber}")
    @ApiOperation("获取学生综测")
    public R<StudentInfoVo> getStudent(@PathVariable String studentNumber) {
        if (log.isDebugEnabled()) {
            log.debug("searchStudent: studentNumber = {}", studentNumber);
        }
        return R.success(studentService.getStudentByStudentNumber(studentNumber));
    }

    /**
     * 通过姓名、学号搜索学生，获得学生综测信息
     *
     * @param keyword 关键字
     * @return 综测信息
     */
    @GetMapping("/getother")
    @ApiOperation("查看其他学生综测")
    public R<List<StudentInfoVo>> getOther(String keyword) {
        if (log.isDebugEnabled()) {
            log.debug("searchStudent: keyword = {}", keyword);
        }
        if (!keyword.isBlank()) {
            return R.success(studentService.getStudentByKeyword(keyword));
        }
        return R.err("搜索关键字不能为空");
    }

    /**
     * 增加学生，需要有root权限
     *
     * @param studentRegisterDto 学生注册信息
     * @param authHeader         jwt
     * @return 是否成功
     */
    @PostMapping("/root/add")
    @ApiOperation("增加学生")
    public R<String> addStudent(@RequestBody StudentRegisterDto studentRegisterDto, @RequestHeader("Authorization") String authHeader) {
        if (log.isDebugEnabled()) {
            log.debug("addStudent: studentRegisterDto = {}", studentRegisterDto);
            log.debug("addStudent: authHeader = {}", authHeader);
        }
        if (jwtUtil.isRoot(authHeader)) {
            Map<String, Object> token = jwtUtil.parseToken(authHeader);
            Claims claims = (Claims) token.get("claims");
            Integer operatorId = claims.get("id", Integer.class);
            studentService.register(studentRegisterDto, operatorId);
            return R.success("增加学生成功");
        } else {
            return R.err("权限不足");
        }
    }

    /**
     * 批量增加学生，需要有root权限
     *
     * @param studentRegisterDtoList 学生注册信息 authHeader
     * @param authHeader             jwt
     * @return 是否成功
     */
    @PostMapping("/root/add/batch")
    @ApiOperation("批量增加学生")
    public R<String> batchAddStudent(@RequestBody List<StudentRegisterDto> studentRegisterDtoList, @RequestHeader("Authorization") String authHeader) {
        if (log.isDebugEnabled()) {
            log.debug("batchAddStudent: studentRegisterDtoList = {}", studentRegisterDtoList);
            log.debug("batchAddStudent: authHeader = {}", authHeader);
        }
        if (jwtUtil.isRoot(authHeader)) {
//		    批量更新
            Map<String, Object> token = jwtUtil.parseToken(authHeader);
            Claims claims = (Claims) token.get("claims");
            Integer operatorId = claims.get("id", Integer.class);
            studentService.addBatch(studentRegisterDtoList, operatorId);
            return R.success("批量增加学生成功");
        }
        return R.err("权限不足");
    }

    /**
     * 删除学生，需要有root权限
     *
     * @param id         学生id
     * @param authHeader jwt
     * @return 是否删除成功
     */
    @DeleteMapping("/root/delete/{id}")
    @ApiOperation("删除学生")
    public R<String> deleteStudent(@PathVariable Integer id, @RequestHeader("Authorization") String authHeader) {
        if (log.isDebugEnabled()) {
            log.debug("deleteStudent: id = {}", id);
            log.debug("deleteStudent: authHeader = {}", authHeader);
        }
        if (jwtUtil.isRoot(authHeader)) {
            studentService.removeById(id);
            studentService.deleteHistory(id);
            return R.success("删除学生成功");
        }
        return R.err("权限不足");
    }

//	/**
//	 * 批量删除学生，需要有root权限
//	 *
//	 * @param idList     学生id列表
//	 * @param authHeader jwt
//	 * @return 是否删除成功
//	 */
//	@DeleteMapping("/root/delete/batch")
//	@ApiOperation("批量删除学生")
//	public R<String> batchDeleteStudent(@RequestParam List<Integer> idList, @RequestHeader("Authorization") String authHeader) {
//		if (log.isDebugEnabled()) {
//			log.debug("batchDeleteStudent: idList = {}", idList);
//			log.debug("batchDeleteStudent: authHeader = {}", authHeader);
//		}
//		return R.success("批量删除学生成功");
//	}

    /**
     * 根据学号、姓名、班级，专业搜索学生,需要有管理员权限
     * <p>搜索栏中的内容不需要处理，直接传给keyword即可</p>
     * keyword为空字符串则查询所有学生
     *
     * @param keyword    关键字，可以是学号或姓名
     * @param authHeader jwt
     * @param pageNumber 当前页数
     * @param pageSize   当前页大小
     * @return 学生信息列表
     */
    @GetMapping("/search")
    @ApiOperation("搜索学生")
    public R<Page<StudentInfoVo>> searchStudent(@RequestParam() String keyword,
                                                @RequestHeader("Authorization") String authHeader,
                                                @RequestParam(defaultValue = "1") Integer pageNumber,
                                                @RequestParam(defaultValue = "10") Integer pageSize) {
        if (log.isDebugEnabled()) {
            log.debug("keyword:{}", keyword);
            log.debug("authHeader:{}", authHeader);
        }
//		提取头部的jwt信息，进行鉴权
        if (jwtUtil.isAdmin(authHeader)) {
//		调用搜索学生方法
            return R.success(studentService.searchStudent(keyword, pageNumber, pageSize));
        }
        return R.err("权限不足");
    }

    /**
     * 根据学号查询姓名
     *
     * @param studentNumber 学号
     * @return 学生姓名
     */
    @GetMapping("/getName/{studentNumber}")
    @ApiOperation("根据学号查询姓名")
    public R<String> getName(@PathVariable String studentNumber, @RequestHeader("Authorization") String authHeader) {
        if (log.isDebugEnabled()) {
            log.debug("getName: studentNumber = {}", studentNumber);
        }
        if (studentNumber == null) {
            return R.err("学号不能为空");
        }
        if (!jwtUtil.isAdmin(authHeader)) {
            return R.err("权限不足");
        }
        return R.success(studentService.getName(studentNumber));
    }

}
